package com.itheima.Controller;


import com.alibaba.druid.sql.visitor.functions.Right;
import com.alibaba.druid.support.logging.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Bean.Employee;
import com.itheima.Service.EmployeeService;
import com.itheima.common.R;
import com.itheima.exception.CustomException;
import com.sun.xml.internal.ws.resources.HttpserverMessages;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.http11.HttpOutputBuffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        log.info("登录！");
        //拿到请求过来的json数据的实体类的密码
        String password = employee.getPassword();
        if(password==null){
            return R.error("密码为空！");
        }
        //将不为空的密码转换成字节后进行md5的加密
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        //创建lqw条件查询的对象
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //判断请求过来的username是否跟所有的类的username相同
        lqw.eq(Employee::getUsername,employee.getUsername());
        //调用Iservice的getone方法
        Employee emp = employeeService.getOne(lqw);
        if(emp==null){
            return R.error("用户不存在！");
        }
        if(!pwd.equals(emp.getPassword())){
            return R.error("密码错误啊！");
        }
        if(emp.getStatus()==0){
            return R.error("该用户已被禁用！");
        }

        //将员工的id存入服务器端的session
        session.setAttribute("employeeID",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest httpServletRequest){
        log.info("退出登录！");
        httpServletRequest.getSession().removeAttribute("employeeID");
        return R.success("已退出账号！");
    }


    @PostMapping
    public R<String> save(HttpSession session,@RequestBody Employee employee){
        log.info("新增员工信息：{}",employee.toString());

        //判断是否已存在该员工
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(lqw);
        if(one != null){
            throw new CustomException("该用户名["+employee.getUsername()+"]已存在");
        }

        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        Long empId = (Long)session.getAttribute("employeeID");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        boolean flag = employeeService.save(employee);
        return flag ? R.success("新增员工成功！"):R.error("新增员工失败！");
    }

    @GetMapping("/page")
    public R<Page<Employee>> pageSelect(@RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "1") int pageSize,String name){
        //创建page对象
        Page page1 = new Page(page,pageSize);

        LambdaQueryWrapper<Employee> lqw  = new LambdaQueryWrapper();
        //名字不为空时，模糊匹配所有employee中的name
        lqw.like(name!=null,Employee::getName,name);

        //调用Iservice的分页查询
        //把page对象和条件查询对象扔进去
        employeeService.page(page1,lqw);

        return R.success(page1);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){

        if(employee.getName()!=null){ //优化：判断用户是否存在或者排除自身
            LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Employee::getName,employee.getName()).ne(Employee::getId,employee.getId());
            if(employeeService.count(lqw) >  0){
                throw new CustomException("该用户已存在！");
            }}

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long) session.getAttribute("employeeID"));
        boolean flag = employeeService.updateById(employee);
        return flag ? R.success("修改成功！") : R.error("修改失败");
    }

     @GetMapping("/{id}")
     public R<Employee> getById(@PathVariable Long id){
        log.info("回显");
         Employee employee = employeeService.getById(id);
         if(employee!=null){
             return R.success(employee);
         }
         return R.error("没有查询到该员工的信息！");
     }




}
